<template>
  <div class="dc">
    <div class="tips">请导入.cer格式的证书文件</div>
    <uploadFile v-bind="signature" />
    <uploadFile v-bind="encryption" />
  </div>
</template>

<script>
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import uploadFile from './components/uploadFile'
import { setUploadFile, getCertificate } from '@/api/upload'
export default {
  name: 'Dc',
  components: { uploadFile },
  data() {
    return {
      signature: {
        title: '签名证书',
        type: 'cer/*',
        isAlready: false,
        uploadInfo: {},
        uploadTxt: this.uploadSignature.bind(this),
        beforeTxtUpload: this.beforeUpload.bind(this)
      },
      encryption: {
        title: '加密证书',
        type: 'cer/*',
        isAlready: false,
        uploadInfo: {},
        uploadTxt: this.uploadEncryption.bind(this),
        beforeTxtUpload: this.beforeUpload.bind(this)
      }
    }
  },
  created() {
    Promise.all([getCertificate({ type: 0 }), getCertificate({ type: 1 })]).then(arr => {
      this.signature.uploadInfo = arr[0].data
      this.signature.isAlready = arr[0].data.state === 1
      this.encryption.uploadInfo = arr[1].data
      this.encryption.isAlready = arr[1].data.state === 1
    }).catch(_ => {
      console.log(_)
    })
  },
  methods: {
    /**
     * 上传签名证书
     * @param param
     */
    uploadSignature(param) {
      NProgress.start()
      setUploadFile({ signFile: param.file, type: 0 }).then(rsp => {
        this.signature.uploadInfo = rsp.data
        this.signature.isAlready = rsp.data.state === 1
        this.$store.dispatch('message/SetMsgInfo', {
          type: 'warning',
          msg: rsp.message
        })
      }).catch(rej => {
        console.log(rej)
      }).finally(_ => {
        NProgress.done()
      })
    },
    /**
     * 上传加密证书
     * @param param
     */
    uploadEncryption(param) {
      NProgress.start()
      setUploadFile({ signFile: param.file, type: 1 }).then(rsp => {
        this.encryption.uploadInfo = rsp.data
        this.encryption.isAlready = rsp.data.state === 1
        this.$store.dispatch('message/SetMsgInfo', {
          type: 'warning',
          msg: rsp.message
        })
      }).catch(rej => {
        console.log(rej)
      }).finally(_ => {
        NProgress.done()
      })
    },
    beforeUpload(file) {
      const isTp = file.type === 'application/x-x509-ca-cert'

      if (!isTp) {
        this.$store.dispatch('message/SetMsgInfo', {
          type: 'warning',
          msg: '请导入.cer格式的证书文件'
        })
      }
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isLt5M) {
        this.$store.dispatch('message/SetMsgInfo', {
          type: 'warning',
          msg: '上传文件大小不能超过 5MB!'
        })
      }
      return isLt5M && isTp
    }
  }
}
</script>

<style lang="scss" scoped>
.dc{
  font-size: 14px;
  .tips{
    margin: 20px 0 ;
    text-indent: 100px;
  }
}
</style>
